import { authenticate } from '@/api/deepin-auth'

export default {
  namespaced: true,
  state: () => ({
    token: null,
    loading: false,
    error: null
  }),
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
    },
    SET_LOADING(state, value) {
      state.loading = value
    },
    SET_ERROR(state, error) {
      state.error = error
    }
  },
  actions: {
    async authenticate({ commit }, credentials) {
      commit('SET_LOADING', true)
      try {
        const token = await authenticate(credentials)
        commit('SET_TOKEN', token)
        commit('SET_ERROR', null)
        return true
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    }
  }
}